#!usr/bin/env python 
#coding=utf8
#Liangqilong 2015.12.28


import psutil,MySQLdb


#统计cpu,network，memory,disk信息
def cpuInfo():
    #定义cpu变量
    times=psutil.cpu_times()
    param=(psutil.cpu_count(),psutil.cpu_percent(),times.user,times.nice,
            times.system,times.idle,times.iowait,times.irp,times.irp,
            times.softirp,times.steal,times.guest)
    sql='''INSET INTO cpu_info(psutil.cpu_count(),psutil.cpu_percent(),times.user,times.nice,
            times.system,times.idle,times.iowait,times.irp,times.irp,times.softirp,times.steal,
            times.guest) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)'''
    return sql,param
    
def memoryInfo():
    #定义memory变量
    virmem=psutil.virtual_memory()
    param=(virmem.total,virmem.buffers,virmem.cached,virmem.active,virmem.inactive,
            virmem.percent,virmem.available,virmem.index)
    sql='''INSET INTO cpu_info(virmem.total,virmem.buffers,virmem.cached,virmem.active,virmem.inactive,
            virmem.percent,virmem.available,virmem.index) VALUES(%s,%s,%s,%s,%s,%s,%s,%s)'''
    return sql,param


def networkInfo():
    #定义network变量
    net=psutil.net_io_counters()
    param=(net.bytes_sent,net.bytes_recv,net.packets_sent,net.packets_recv,net.errin,
            net.errout,net.dropin,net.dropout)
    sql='''INSET INTO cpu_info(net.bytes_sent,net.bytes_recv,net.packets_sent,net.packets_recv,
            net.errin,net.errout,net.dropin,net.dropout) VALUES(%s,%s,%s,%s,%s,%s,%s,%s)'''
    return sql,param


def disksInfo():
    #定义disk根目录变量
    disk=psutil.disk_usage('/')
    param=(disk.total,disk.used,disk.free,disk.percent)
    sql="INSET INTO cpu_info(disk.total,disk.used,disk.free,disk.percent) VALUES(%s,%s,%s,%s)"
    return sql,param


#连接到数据库
def getConn():
    result=MySQLdb.connect(host=config.host,port=config.port,user=config.user,
                           passwd=config.passwd,db=config.dbname)
    return result


#添加到数据库
def addMysql():
    conn=getConn()
    cur=conn.cursor()
    sql_param=(cpuInfo(),memoryInfo(),networkInfo(),disksInfo())
    for value in sql_param:
          sql,param=value
          cursor.execute(sql,param)
          conn.commit()
    cur.close()
    conn.close()








          
   
